import HighCharts from "highcharts"
import Highmaps from "highcharts/modules/map"
Highmaps(HighCharts)
HighCharts.setOptions({
    lang: {
        resetZoom: "重置缩放比例",
    },
})
import highchartsMore from "highcharts/highcharts-more"
highchartsMore(HighCharts)
function initWebControl(options, cbk) {
    getPubKey(function() {
        ////////////////////////////////// 请自行修改以下变量值	////////////////////////////////////
        var appkey = "24769112" //综合安防管理平台提供的appkey，必填 28637202
        var secret = setEncrypt("NxjYIfempoqQaVtRqKLF") //综合安防管理平台提供的secret，必填 6gRK4YqLhPumVHN2tOuj
        var ip = "122.4.227.102" //综合安防管理平台IP地址，必填
        var playMode = options.playMode == 1 ? 1 : 0 //初始播放模式：0-预览，1-回放
        var port = 4433 //综合安防管理平台端口，若启用HTTPS协议，默认443
        var snapDir = "C:\\SnapDir" //抓图存储路径
        var videoDir = "C:\\VideoDir" //紧急录像或录像剪辑存储路径
        var layout = options.layout || "1x1" //playMode指定模式的布局
        var enableHTTPS = 1 //是否启用HTTPS协议与综合安防管理平台交互，这里总是填1
        var encryptedFields = "secret" //加密字段，默认加密领域为secret
        var showToolbar = 0 //是否显示工具栏，0-不显示，非0-显示
        var showSmart = 1 //是否显示智能信息（如配置移动侦测后画面上的线框），0-不显示，非0-显示
        var buttonIDs = "0,16,256,257,258,259,260,512,513,514,515,516,517,768,769" //自定义工具条按钮
        ////////////////////////////////// 请自行修改以上变量值	////////////////////////////////////

        oWebControl
            .JS_RequestInterface({
                funcName: "init",
                argument: JSON.stringify({
                    appkey: appkey, //API网关提供的appkey
                    secret: secret, //API网关提供的secret
                    ip: ip, //API网关IP地址
                    playMode: playMode, //播放模式（决定显示预览还是回放界面）
                    port: port, //端口
                    snapDir: snapDir, //抓图存储路径
                    videoDir: videoDir, //紧急录像或录像剪辑存储路径
                    layout: layout, //布局
                    enableHTTPS: enableHTTPS, //是否启用HTTPS协议
                    encryptedFields: encryptedFields, //加密字段
                    showToolbar: showToolbar, //是否显示工具栏
                    showSmart: showSmart, //是否显示智能信息
                    buttonIDs: buttonIDs, //自定义工具条按钮
                }),
            })
            .then(function(oData) {
                oWebControl.JS_Resize(options.width, options.height) // 初始化后resize一次，规避firefox下首次显示窗口后插件窗口未与DIV窗口重合问题
                if (cbk) cbk()
            })
    })
}
//获取公钥
function getPubKey(callback) {
    oWebControl
        .JS_RequestInterface({
            funcName: "getRSAPubKey",
            argument: JSON.stringify({
                keyLength: 1024,
            }),
        })
        .then(function(oData) {
            console.log(oData)
            if (oData.responseMsg.data) {
                pubKey = oData.responseMsg.data
                callback()
            }
        })
}

//RSA加密
function setEncrypt(value) {
    var encrypt = new JSEncrypt()
    encrypt.setPublicKey(pubKey)
    return encrypt.encrypt(value)
}
// 推送消息
function cbIntegrationCallBack(oData) {
    console.log(JSON.stringify(oData.responseMsg))
}
Date.prototype.Format = function(fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        S: this.getMilliseconds(), //毫秒
    }
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length))
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
            )
    return fmt
}
export default {
    getUrlParam() {
        let searchArr = window.location.href.split("?")
        let search = searchArr.length > 1 ? searchArr[1].split("&") : []
        let param = {}
        if (search.length > 0 && search[0].length > 0) {
            search.forEach((item) => {
                let temp = item.split("=")
                param[temp[0]] = temp[1]
            })
        }
        return param
    },
    // 设置Storage
    setStorage(key, value) {
        if ((typeof value).toLowerCase() == "object") {
            value = JSON.stringify(value)
        }
        window.localStorage.setItem(key, value)
    },
    // 获取Storage
    getStorage(key) {
        let value = window.localStorage.getItem(key)
        if (value && value.indexOf("{") >= 0 && value.indexOf("}") >= 0) {
            return JSON.parse(value)
        }
        return value
    },
    // 删除Storage
    removeStorage(key) {
        window.localStorage.removeItem(key)
    },
    // 清空Storage
    clearStorage() {
        window.localStorage.clear()
    },
    // 设置cookie
    setCookie(cname, cvalue, exdays) {
        let d = new Date()
        d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000)
        let expires = "expires=" + d.toUTCString()
        document.cookie = cname + "=" + cvalue + "; " + expires
    },

    // 获取cookie
    getCookie(cname) {
        let name = cname + "="
        let ca = document.cookie.split(";")
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i]
            while (c.charAt(0) === " ") c = c.substring(1)
            if (c.indexOf(name) !== -1) return c.substring(name.length, c.length)
        }
        return null
    },

    // 清除cookie
    clearCookie() {
        this.setCookie("username", "", -1)
    },
    //时间戳转时间
    timestamp2datetime(timestamp) {
        var time = new Date(timestamp)
        var y = time.getFullYear()
        var m = time.getMonth() + 1
        var d = time.getDate()
        var h = time.getHours()
        var mm = time.getMinutes()
        var s = time.getSeconds()
        return (
            y +
            "-" +
            this.formatNum(m) +
            "-" +
            this.formatNum(d) +
            " " +
            this.formatNum(h) +
            ":" +
            this.formatNum(mm) +
            ":" +
            this.formatNum(s)
        )
    },
    formatNum(m) {
        m = Number(m)
        return m < 10 ? "0" + m : m
    },
    RMBToCapital(money) {
        var fraction = ["角", "分"],
            digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"],
            unit = [
                ["元", "万", "亿"],
                ["", "拾", "佰", "仟"],
            ],
            head = money < 0 ? "欠" : ""
        money = Math.abs(money)
        var s = ""
        for (var i = 0; i < fraction.length; i++) {
            s += (digit[Math.floor(money * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(
                /零./,
                ""
            )
        }
        s = s || "整"
        money = Math.floor(money)

        for (var i = 0; i < unit[0].length && money > 0; i++) {
            var p = ""
            for (var j = 0; j < unit[1].length && money > 0; j++) {
                p = digit[money % 10] + unit[1][j] + p
                money = Math.floor(money / 10)
            }
            s = p.replace(/(零.)*零$/, "").replace(/^$/, "零") + unit[0][i] + s
        }
        return (
            head +
            s
                .replace(/(零.)*零元/, "元")
                .replace(/(零.)+/g, "零")
                .replace(/^整$/, "零元整")
        )
    },
    getDocSize() {
        let winW = document.documentElement.clientWidth || document.body.clientWidth
        let winH = document.documentElement.clientHeight || document.body.clientHeight
        let docSize = {
            width: winW,
            height: winH,
        }
        return docSize
    },
    pick(obj, arr) {
        return arr.reduce((item, val) => {
            if (val in obj) {
                item[val] = obj[val]
            }
            return item
        }, {})
    },
    toTree(data) {
        let result = []
        if (!Array.isArray(data)) {
            return result
        }
        data.forEach((item) => {
            delete item.children
        })
        let map = {}
        data.forEach((item) => {
            map[item.id] = item
        })
        data.forEach((item) => {
            let parent = map[item.parentId]
            if (parent) {
                ;(parent.children || (parent.children = [])).push(item)
            } else {
                result.push(item)
            }
        })
        return result
    },
    getCurrentDate(px) {
        let currentDate = new Date()
        let year = currentDate.getFullYear()
        let month = currentDate.getMonth() + 1
        let day = currentDate.getDate()
        return [year, month, day].join("-")
    },
    renderSpline(opts) {
        HighCharts.setOptions({
            timezoneOffset: -8,
        })
        let { id, chartData, scale, width, height } = opts
        scale = scale || 1
        if (!chartData) return
        width = scale * width
        height = scale * height
        let unit = opts.unit ? opts.unit : ""
        let data = chartData
        let options = {
            lang: {
                resetZoom: "还原",
            },
            credits: {
                enabled: false,
            },
            colors: ["#5AD8A6", "#F6BD16", "#5B8FF9", "#9270CA"],
            chart: {
                type: "spline",
                width: width,
                height: height,
                backgroundColor: "transparent",
                spacing: 0,
                margin: [50 * scale, 0, 30, 80 * scale],
                zoomType: "x",
                panning: true,
                panKey: "shift",
            },
            mapNavigation: {
                enabled: true,
                enableButtons: false,
            },
            title: {
                text: "",
            },
            xAxis: {
                title: {
                    text: null,
                },
                labels: {
                    style: {
                        color: "#AFECFF",
                        fontSize: 10 * scale,
                    },
                },
                lineColor: "#85b4d0",
                type: "datetime",
                dateTimeLabelFormats: {
                    millisecond: "%H:%M:%S.%L",
                    second: "%H:%M:%S",
                    minute: "%H:%M",
                    hour: "%H:%M",
                    day: "%m-%d",
                    week: "%m-%d",
                    month: "%Y-%m",
                    year: "%Y",
                },
            },
            yAxis: {
                title: {
                    text: null,
                },
                labels: {
                    style: {
                        color: "#AFECFF",
                        fontSize: 12 * scale,
                    },
                    formatter: function() {
                        return this.value + unit
                    },
                },
                minorGridLineWidth: 0,
                lineWidth: 0,
                tickWidth: 0,
                tickPosition: "inside",
                tickmarkPlacement: "between",
                tickColor: "#AFECFF",
                gridLineWidth: 1,
                gridLineColor: "#57789a",
                // tickInterval:10
            },
            legend: {
                enabled: true,
                align: "right",
                float: true,
                verticalAlign: "top",
                itemStyle: {
                    color: "#AFECFF",
                    fontSize: 12 * scale + "px",
                },
                itemHoverStyle: {
                    color: "#ffffff",
                },
                // itemMarginBottom: 5*scale,
                // squareSymbol: false,
                symbolWidth: 24 * scale,
                // symbolHeight: 2*scale,
                // symbolPadding: 5*scale,
                symbolRadius: 2 * scale,
                // lineHeight: 0,
                // width: '60%'
            },
            tooltip: {
                shared: true,
                valueSuffix: unit || "",
                dateTimeLabelFormats: {
                    millisecond: "%H:%M:%S.%L",
                    second: "%H:%M:%S",
                    minute: "%H:%M",
                    hour: "%H:%M",
                    day: "%Y-%m-%d",
                    week: "%m-%d",
                    month: "%Y-%m",
                    year: "%Y",
                },
            },
            plotOptions: {
                spline: {
                    dataLabels: {
                        enabled: false,
                    },
                    marker: {
                        enabled: true,
                        radius: 3 * scale,
                        lineWidth: 1,
                    },
                    pointInterval: 3600000, // one hour
                },
            },
            series: data.series,
        }
        HighCharts.chart(id, options)
    },
    renderBar(opts) {
        let { id, chartData, scale, width, height } = opts
        scale = scale || 1
        // console.log(id,chartData,scale)
        if (!chartData) return
        width = scale * width
        height = scale * height
        let data = chartData
        let options = {
            credits: {
                enabled: false,
            },
            colors: ["#3F95FF", "#F6BD16", "#5B8FF9", "#9270CA"],
            chart: {
                type: "column",
                width: width,
                height: height,
                backgroundColor: "transparent",
                spacing: 0,
                margin: [20 * scale, 0 * scale, 30 * scale, 50 * scale],
            },
            title: {
                text: "",
            },
            xAxis: {
                categories: data.categories,
                title: {
                    text: null,
                },
                labels: {
                    style: {
                        color: "#AFECFF",
                        fontSize: 8 * scale,
                    },
                },
                lineColor: "#85b4d0",
            },
            yAxis: {
                title: {
                    text: null,
                },
                labels: {
                    style: {
                        color: "#AFECFF",
                        fontSize: 12 * scale,
                    },
                },
                minorGridLineWidth: 0,
                lineWidth: 0,
                tickWidth: 0,
                tickPosition: "inside",
                tickmarkPlacement: "between",
                tickColor: "#AFECFF",
                gridLineWidth: 1,
                gridLineColor: "#57789a",
                // tickInterval:10
            },
            legend: {
                enabled: false,
            },
            tooltip: {
                shared: true,
            },
            plotOptions: {
                column: {
                    borderWidth: 0,
                    pointWidth: 20 * scale,
                },
            },
            series: data.series,
        }
        HighCharts.chart(id, options)
    },
    initVideoWebPlugin(options, callback) {
        // containerId,width,height
        oWebControl = new WebControl({
            szPluginContainer: options.containerId, // 指定容器id
            iServicePortStart: 15900, // 指定起止端口号，建议使用该值
            iServicePortEnd: 15909,
            szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11", // 用于IE10使用ActiveX的clsid
            cbConnectSuccess: function() {
                // 创建WebControl实例成功
                oWebControl
                    .JS_StartService("window", {
                        // WebControl实例创建成功后需要启动服务
                        dllPath: "./VideoPluginConnect.dll", // 值"./VideoPluginConnect.dll"写死
                    })
                    .then(
                        function() {
                            // 启动插件服务成功
                            oWebControl.JS_SetWindowControlCallback({
                                // 设置消息回调
                                cbIntegrationCallBack: cbIntegrationCallBack,
                            })

                            oWebControl
                                .JS_CreateWnd(options.containerId, options.width, options.height)
                                .then(function() {
                                    //JS_CreateWnd创建视频播放窗口，宽高可设定
                                    initWebControl(options, callback) // 创建播放实例成功后初始化
                                })
                        },
                        function() {
                            // 启动插件服务失败
                        }
                    )
            },
            cbConnectError: () => {
                // 创建WebControl实例失败
                oWebControl = null
                $("#" + options.containerId).html("插件未启动，正在尝试启动，请稍候...")
                WebControl.JS_WakeUp("VideoWebPlugin://") // 程序未启动时执行error函数，采用wakeup来启动程序
                initCount++
                if (initCount < 3) {
                    setTimeout(() => {
                        this.initVideoWebPlugin(options, callback)
                    }, 3000)
                } else {
                    $("#" + options.containerId).html(
                        "插件启动失败，请<a class='underline color-blue' href='https://xf.wiscloud.online/uploads/ziliao/VideoWebPlugin.exe'>下载并安装插件</a>！(注：插件仅支持谷歌浏览器及360浏览器极速模式)"
                    )
                }
            },
            cbConnectClose: function(bNormalClose) {
                // 异常断开：bNormalClose = false
                // JS_Disconnect正常断开：bNormalClose = true
                console.log("cbConnectClose")
                oWebControl = null
            },
        })
    },
}
// date.js
// 用于格式化时间
export function formatDate (date, fmt) {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
	let gType=date.getMinutes()
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
        }
    }
    return fmt;
};

function padLeftZero (str) {
    return ('00' + str).substr(str.length);
};
